//
//  SSWorkContentController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/9/11.
//

import UIKit

import SnapKit
import HandyJSON

class SSWorkContentController: SSBaseViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var orderNum = ""
    
    var workContent = SSWorkContent()
    var sumLab = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        getRewardRecord()
        
        title = "工作内容"

        self.tableView.backgroundColor = UIColor.themeBlueColor
        
        self.tableView.register(UINib(nibName: "SSWorkContentCell", bundle: Bundle.init(for: SSWorkContentCell.self)), forCellReuseIdentifier: "SSWorkContentCell")
        
        let footerView = UIView()
        footerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 270)
        footerView.backgroundColor = UIColor.themeBlueColor
        self.tableView.tableFooterView = footerView
        self.tableView.separatorStyle = .none
        self.tableView.tableHeaderView = UIView()
        
        let sumLab = UILabel()
        sumLab.textAlignment = .right
        sumLab.textColor = UIColor(hex: "#E95515")
        sumLab.font = UIFont.systemFont(ofSize: 16)
        sumLab.frame = CGRect(x: ScreenWidth - 200 - 20, y: 70, width: 200, height: 20)
        footerView.addSubview(sumLab)
        self.sumLab = sumLab
        
        let btn = SSCommondButton()
        btn.setTitle("提交", for: .normal)
        footerView.addSubview(btn)
        btn.addTarget(self, action: #selector(btnAction(_:)), for: .touchUpInside)
        btn.snp.makeConstraints { make in
            make.top.equalTo(180)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(56)
        }
        
    }

    @objc func btnAction(_ btn:UIButton){
        debugPrint("1")
        
        var listWorkDic:Array<Any> = []
        var dic = [
            "hourlyRate": workContent.hourlyRate,
            "orderNo": orderNum,
            "phoneNo": kUserPhone,
        ] as [String : AnyObject]
        for item in self.workContent.listWork {
            if(item.itemCount > 0){
                let dicM = [
                    "itemName": item.itemName,
                    "itemQuantity": item.itemCount,
                    "timeLimit": item.timeLimit,
                    "incomeRatio": item.incomeRatio,
                    "maximumQuantity": item.maximumQuantity
                ] as [String : AnyObject]
                listWorkDic.append(dicM)
            }
        }
        dic["listWork"] = listWorkDic as AnyObject
        if(listWorkDic.count == 0){
            self.view.makeToast("请选择项目")
            return
        }
        
        submitNetwork(dic: dic)
        
    }
    
    func handleSum() {
        var totalTime:Float = 0.0
        for item in workContent.listWork{
            if(item.incomeRatio > 0){
                totalTime = totalTime + item.incomeRatio * item.timeLimit * item.itemCount
            }else{
                totalTime = totalTime + item.timeLimit * item.itemCount
            }
        }
        totalTime = totalTime * workContent.hourlyRate
        self.sumLab.text = "总收入：$\(totalTime)"
    }
    

}

extension SSWorkContentController: UITableViewDelegate, UITableViewDataSource
{
    func numberOfSections(in tableView: UITableView) -> Int {
//        return self.items.count
        return 1
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 24 + 16 + 6
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return workContent.listWork.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SSWorkContentCell") as! SSWorkContentCell
        cell.model = workContent.listWork[indexPath.row]
        cell.callback {
            self.handleSum()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 88
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let title = workContent.unitName
//        if self.items.count > 0 {
//            title = (self.items[section] ).name
//        }
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 24 + 16 + 6))
        view.backgroundColor = UIColor.themeBlueColor
        
//        let sectionView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 6))
//        sectionView.backgroundColor = UIColor.init(hex: "#e5e5e5")
//        view.addSubview(sectionView)
        
        
        let label = UILabel()
        label.text = title
        label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        label.textColor = UIColor.black
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.width.equalTo(150)
            make.height.equalTo(26)
            make.centerY.equalTo(view.frame.size.height/2)
            make.left.equalTo(20)
        }
        return view
    }
}


extension SSWorkContentController {
    func getRewardRecord() {
        let param = [
            "phoneNo": kUserPhone,
            "orderNo": orderNum
        ]as[String:AnyObject]
        SSNetwrokManager.share.request(urlString: APIUrl.share.getEMPWork_URL,
                                       parameters:param) { result in
            guard let workContent = SSWorkContent.deserialize(from: result, designatedPath:"data") else {
                return
            }
            self.workContent = workContent
            self.tableView.reloadData()
            print("")
        }
    }
    
    func submitNetwork(dic:[String:AnyObject]) {
 
        SSNetwrokManager.share.request(urlString: APIUrl.share.workCommit_URL,
                                       parameters:dic) { result in
//            guard let workContent = SSWorkContent.deserialize(from: result, designatedPath:"data") else {
//                return
//            }
//            self.workContent = workContent
//            self.tableView.reloadData()
            self.navigationController?.popViewController(animated: true)
            UIViewController.current().view.makeToast("提交成功")
            print("")
        }
    }
}

class SSWorkContent: HandyJSON {
    var hourlyRate: Float = 0
    
    var imgUrl: String = ""
    var itemName: String = ""
    var unitName: String = ""
    
    var incomeRatio: Float = 0.0
    var maximumQuantity: Float = 0.0
    var timeLimit: Float = 0.0
    var itemCount: Float = 0
    var listWork = [SSWorkContent]()

    required init() {}
}
